#! /usr/bin/env python
# process pairwise brain images. 


# use __future__ to run in Python 2.5.X 
from __future__ import with_statement
import sys  
import os
import ConfigParser
import logging
import subprocess
import glob
#sys.path.append("~/projects/FXTAS/tools")

###### parameter parsing #####
if len(sys.argv) < 2:
	print 'usage'
	print '-----'
	print ''
	print 'pairwise config_file'
	print ' '
	print 'Inputs:'
	print '-------'
	print 'The configuration file that discribes the jobs and the dispatching setup.'
	print 'For more information please refer to the in-line comments in the example.conf.'
	sys.exit(1)


###### read in configuration file ##### 
config=ConfigParser.SafeConfigParser(defaults=dict({"working_directory":'.',"diagonal":'1'}))
config_file = os.path.abspath(os.path.expanduser(sys.argv[1]))
if os.path.exists(config_file):
    config.read(config_file)
else:
    print 'config_file does not exist'
    sys.exit(1)

python = os.path.abspath(os.path.expanduser(config.get('pairwise','python')))
engine = os.path.abspath(os.path.expanduser(config.get('pairwise','engine')))
job_name = config.get('pairwise','job_name')
image_directory = os.path.expanduser(config.get('pairwise','image_directory'))
working_directory = os.path.expanduser(config.get('pairwise','working_directory'))
action= config.get('pairwise','action')

os.chdir(working_directory)
#if not os.path.isdir(job_name): 
#    os.mkdir(job_name)
#
#os.chdir(job_name)
 
###### preparing log facility #####
# TODO: use logging.config functionality so that all the setting can be read and changed
# in the configuration file

log_file = job_name+'.log' 
log_level = config.getint('pairwise', 'log_level')
logger = logging.getLogger(job_name)
fh = logging.FileHandler(log_file,"w")
fh.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
if log_level <= logging.INFO:  # in debugging mode, displace logs to stdout
    ch = logging.StreamHandler()
    ch.setLevel(log_level)
    ch.setFormatter(formatter)
    logger.addHandler(ch)

logger.setLevel(log_level)
logger.debug("job: "+job_name+" started ...")

# Start actions

list1=config.get('pairwise','brains').split(',')
list1=map(lambda x: x.strip(), list1)
list2=config.get('pairwise','brains').split(',')
list2=map(lambda x: x.strip(), list2)

f_diagonal=config.getboolean('pairwise','diagonal')

for brain1 in list1:
    #image1=image_directory+"/"+brain1+".hdr" 
    for brain2 in list2:
        #image2=image_directory+"/"+brain2+".hdr" 
        if (brain1 == brain2) and not f_diagonal : 
	    continue
        job_id= job_name+"_"+action 
	pair_directory=brain1+"-"+brain2
	if not os.path.isdir(pair_directory): 
	    os.mkdir(pair_directory)
	os.chdir(pair_directory)
	if action == "clean":
	    try:
	        os.remove("core")
	    except OSError as err:
		if err.args[0] == 2: # No such file or direcotry
		    pass
                else:
                    raise
	    for filename in glob.glob(job_name+"*"):  # log files from SGE
	        os.remove(filename)
	else:
	    subprocess.check_call(["qsub","-l","mem_free=4G","-cwd", "-N", job_id, "-S", python, engine, config_file, action, brain1, brain2, image_directory, pair_directory]) 
	os.chdir(working_directory)
